/****************************************************************************************/
/*																						*/
/*					Tianwan NPP FHM CCS movements stop program							*/
/*																						*/
/*	Author:		M.Tavella																*/
/*	Date:		11/11/2002																*/
/*	Last Mod.:	11/11/2002																*/
/*																						*/
/****************************************************************************************/
#include <windows.h>
#include "ApmsApi.h"
#include "Tianwan.h"
#include "Uti_Tianwan.h"

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow){
	RETSTAT			retSt;
	RETCOND			retCnd;
	TAGIDX			tagIdx;
	TAGVALEX		tagVal;
	DWORD			opStation;
	TCHAR			msg[256];

	retCnd = ApmsApiSrvConnect(NULL, NULL, &opStation);
	if(retCnd != R_NORMAL){
		_stprintf_s(msg, _T("Error connecting Apms Api server. Cannot stop movement."));
		MessageBox(NULL, msg, _T("Error"), MB_OK | MB_ICONERROR);
		return(-1);
	}

	retCnd = GetTagIdx(TWN_START_MOV, &tagIdx);
	if(retCnd != R_NORMAL){
		_stprintf_s(msg, _T("Error retrieving tag \"%s\" identifier. Cannot stop movement."), TWN_START_MOV);
		MessageBox(NULL, msg, _T("Error"), MB_OK | MB_ICONERROR);
		ApmsApiSrvDisconnect();
		return(-1);
	}

	retCnd = TagRead(&tagIdx, &tagVal);
	if(retCnd != R_NORMAL){
		_stprintf_s(msg, _T("Error reading tag \"%s\" value. Cannot stop movement."), TWN_START_MOV);
		MessageBox(NULL, msg, _T("Error"), MB_OK | MB_ICONERROR);
		ApmsApiSrvDisconnect();
		return(-1);
	}

	if(GtBit((unsigned short)(tagVal.value.val_di), 15) == 0){
		MessageBox(NULL, _T("No movement in progress."), _T("Warning"), MB_OK | MB_ICONINFORMATION);
		ApmsApiSrvDisconnect();
		return(1);
	}
	
	retSt = VotedTagWrite(TWN_START_MOV, 0, 0, DIG_VALUE);
	if(retSt != RT_NORMAL){
		_stprintf_s(msg, _T("Error writing tag \"%s\" value. Cannot stop movement."), TWN_START_MOV);
		MessageBox(NULL, msg, _T("Error"), MB_OK | MB_ICONERROR);
		ApmsApiSrvDisconnect();
		return(-1);
	}

	ApmsApiSrvDisconnect();
	return(1);
}